﻿Ext.namespace("Swfu");
Ext.namespace("Swfu.BackMgr");

Swfu.BackMgr.AllRolesDS = new Ext.data.Store(
{
    url: '/roles.mvc/FindAll_roles', autoLoad: false, reader: new Ext.data.JsonReader({
        fields: [{
            name: "roleid"
        },
        {
            name: "rolename"
        }]
    })
});

Swfu.BackMgr.UserMgr = Ext.extend(Ext.grid.EditorGridPanel,
{
    initComponent: function () {
        Swfu.BackMgr.AllRolesDS.reload();
        var Plant = Ext.data.Record.create([{
            name: 'username'
        },
        {
            name: 'roleid'
        },
        {
            name: 'telephone'
        },
        {
            name: 'usersex'
        },
        {
            name: 'address'
        },
        {
            name: 'email'
        },
        {
            name: 'password'
        },
        {
            name: 'logintime'
        },
        {
            name: 'createtime'
        }]);
        var sm = new Ext.grid.CheckboxSelectionModel();
        var fm = Ext.form;
        var cm = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(), sm,
        {
            header: "用户名", sortable: true, dataIndex: 'username', editor: new fm.TextField({
                allowBlank: false
            })
        },
        {
            header: "性别", sortable: true, dataIndex: 'usersex', editor: new Ext.form.ComboBox(
            {
                id: 'usersex', name: 'usersex', displayField: 'nv', valueField: 'nv', hiddenName: 'nv',
                hiddenId: 'nv', typeAhead: true, mode: 'local', editable: false, selectOnFoucs: true,
                triggerAction: 'all', allowBlank: false, blankText: '请选择性别', emptyText: '请选择性别', store: new Ext.data.SimpleStore({
                    fields: ['nv'], data: [['男'], ['女']], autoload: true
                }), listeners: {
                    scope: this
                }
            })
        },
        {
            header: "电话号码", sortable: true, dataIndex: 'telephone', editor: new fm.TextField({
                allowBlank: true
            })
        },
        {
            header: "地址", sortable: true, dataIndex: 'address', editor: new fm.TextField({
                allowBlank: true
            })
        },
        {
            header: "电子邮件", sortable: true, dataIndex: 'email', editor: new fm.TextField({
                allowBlank: true
            })
        },
        {
            header: "用户角色", sortable: true, dataIndex: 'roleid', typeAhead: true, editor: new Ext.form.ComboBox(
            {
                id: 'cboRole', name: 'cboRole', displayField: 'rolename', valueField: 'roleid', hiddenName: 'roleid',
                hiddenId: 'roleid', typeAhead: true, mode: 'remote', editable: false, selectOnFoucs: true,
                triggerAction: 'all', allowBlank: false, blankText: '请选择角色', emptyText: '请选择角色', store: Swfu.BackMgr.AllRolesDS
            }),
            renderer: function (value, cellmeta, record) {
                Swfu.BackMgr.AllRolesDS.reload();
                var index = Swfu.BackMgr.AllRolesDS.find(Ext.getCmp('cboRole').valueField, value);
                if (index >= 0) {
                    var record = Swfu.BackMgr.AllRolesDS.getAt(index);
                    if (record) {
                        return record.data.rolename;
                    }
                }
                else {
                    Swfu.BackMgr.AllRolesDS.load();
                    return "未指定";
                }
            }
        },

        {
            header: "最后登录", sortable: true, hidden: true, dataIndex: 'logintime', editor: new fm.TextField({
                allowBlank: true
            })
        },

        {
            header: "创建时间", sortable: true, hidden: true, dataIndex: 'createtime', editor: new fm.TextField({
                allowBlank: true
            })
        }]);
        var reader = new Ext.data.JsonReader(
        {
            totalProperty: "totalSize", autoLoad: true, fields: [{
                name: 'userid'
            },
            {
                name: 'username'
            },
            {
                name: 'password'
            },
            {
                name: 'roleid'
            },
            {
                name: 'telephone'
            },
            {
                name: 'usersex'
            },
            {
                name: 'address'
            },
            {
                name: 'email'
            },
            {
                name: 'logintime'
            },
            {
                name: 'createtime'
            }]
        });
        var ds = new Ext.data.Store(
        {
            scopte: this, url: '/userinfo.mvc/FindAll_userinfo', reader: reader, sortInfo: {
                field: 'username', direction: "ASC"
            }
        });
        Ext.apply(this,
        {
            plain: true, layout: 'fit', border: false, cm: cm, sm: sm, frame: true, store: ds,
            loadMask: true, clicksToEdit: 1, tbar: [
            {
                text: '添加', iconCls: 'icon-edit',
                handler: function () {
                    var p = new Plant(
                    {
                        isNew: '1', 'username': '', 'telephone': '', 'roleid': '', 'usersex': '',
                        'address': '', 'email': '', 'password': '', 'logintime': '', 'createtime': ''
                    });
                    this.stopEditing();
                    ds.insert(0, p);
                    this.startEditing(0, 0)
                }
                .createDelegate(this)
            },
            '-',
            {
                text: '删除', id: 'delGuestBtn', iconCls: 'icon-delete', minWidth: '50',
                handler: function () {
                    var selections = this.selModel.getSelections();
                    store = this.getStore();
                    var n = selections.length;
                    if (n == 0) {
                        Ext.ux.Toast.msg("提示", "请选择其中一项！");
                        return
                    }
                    if (n == store.getCount()) {
                        Ext.ux.Toast.msg("提示", "请至少保留一个管理员账号！");
                        return
                    }
                    Ext.Msg.show(
                    {
                        title: '系统确认', msg: '你是否确定删除此记录?删除的数据无法恢复！', buttons: Ext.Msg.YESNO, scope: this,
                        fn: function (btn) {
                            if (btn == 'yes') {
                                var rds = [];
                                for (var i = 0; i < n; i++) {
                                    rds.push(selections[i].data);
                                    store.remove(selections[i])
                                }
                                var rdsjson = Ext.util.JSON.encode(rds);
                                this.deleteSelectedRows(rdsjson)
                            }
                            else { }
                        },
                        icon: Ext.MessageBox.QUESTION
                    })
                }
                .createDelegate(this)
            },
            '-',
            {
                text: "重新加载数据", iconCls: 'icon-redo',
                handler: function () {
                    ds.reload()
                }
                .createDelegate(this)
            },
            '-',
            {
                text: "保存", iconCls: 'icon-save',
                handler: function () {
                    var record;
                    var grid = this.getStore();
                    grid.each(function (rs) {
                        if (rs.get('isNew') == '1') {
                            record = rs;
                            if (rs.get('username').trim() == '' || rs.get('roleid') == '') {
                                Ext.ux.Toast.msg('提示', '数据不完整，请重新输入...');
                                return
                            }
                            this.jsonData = Ext.util.JSON.encode(record.data);
                            Ext.Ajax.request(
                            {
                                url: '/userinfo.mvc/Add_userinfo',
                                success: function () {
                                    Ext.ux.Toast.msg('提示', '已经成功保存新添加的数据。');
                                    ds.reload()
                                },
                                failure: function () {
                                    Ext.Msg.alert("错误", "更新数据库失败,请重新操作.")
                                },
                                params: {
                                    json: this.jsonData
                                },
                                waitMsg: '保存数据中...'
                            })
                        }
                        else if (rs.dirty) {
                            record = rs;
                            this.jsonData = Ext.util.JSON.encode(record.data);
                            Ext.Ajax.request(
                            {
                                url: '/userinfo.mvc/Update_userinfo',
                                success: function () {
                                    Ext.ux.Toast.msg('提示', '已经成功保存修改的数据。');
                                    ds.reload()
                                },
                                failure: function (action) {
                                    if (action.failureType == 'server') {
                                        obj = Ext.util.JSON.decode(action.response.responseText);
                                        Ext.Msg.alert('错误:', obj.errors.reason)
                                    }
                                },
                                params: {
                                    json: this.jsonData
                                },
                                waitMsg: '保存数据中...'
                            })
                        }
                    });
                    grid.commitChanges()
                }
                .createDelegate(this)
            }], loadMask: true
        });
        Swfu.BackMgr.UserMgr.superclass.initComponent.apply(this, arguments);
        ds.load({
            params: {
                start: 0, limit: 20
            }
        })
    },
    deleteSelectedRows: function (rds) {
        var ds = this.getStore();
        Ext.Ajax.request(
        {
            url: '/userinfo.mvc/Del_userinfo',
            success: function (response, options) {
                var responseMessage = Ext.util.JSON.decode(response.responseText);
                if (responseMessage.Result) {
                    ds.reload();
                    Ext.ux.Toast.msg('提示', '已经成功删除选中的数据。')
                }
                else {
                    Ext.ux.Toast.msg('提示', '删除失败，请您重试。')
                }
            },
            failure: function (action) {
                if (action.failureType == 'server') {
                    obj = Ext.util.JSON.decode(action.response.responseText);
                    Ext.Msg.alert('错误:', obj.errors.reason)
                }
            },
            params: {
                json: rds
            }
        })
    }
});
Ext.reg('UserMgr', Swfu.BackMgr.UserMgr);